package com.axend.aerosense.room.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.activity.MvvmBaseActivity;
import com.axend.aerosense.base.bean.BaseBean;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.bean.BindRoomBean;
import com.axend.aerosense.common.bean.GetRadarList;
import com.axend.aerosense.common.bean.MoveBindRoomBean;
import com.axend.aerosense.common.bean.RadarBean;
import com.axend.aerosense.common.bean.RadarType;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.databinding.CommonLayoutBottomDialogBinding;
import com.axend.aerosense.common.databinding.CommonLayoutTopDialogBinding;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.ui.CommonPopupWindow;
import com.axend.aerosense.common.ui.CustomTipsDialog;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomActivityDeviceListBinding;
import com.axend.aerosense.room.entity.RoomUnassignedBean;
import com.axend.aerosense.room.ui.adapter.RoomDeviceListAdapter;
import com.axend.aerosense.room.viewmodel.RoomDeviceListViewModel;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class RoomDeviceListActivity
        extends MvvmBaseActivity<RoomActivityDeviceListBinding, RoomDeviceListViewModel>
        implements ILoadDataResult<BaseBean> {

    public static final int BING_REQUEST_CODE = 666;
    public static final int BING_RESULT_CODE = 23;
    public static final String PAGER_FLAG = "PAGER_FLAG";
    public static final String ROOM_UUID = "ROOM_UUID";
    public static final String ROOM_NAME = "ROOM_NAME";
    public static final int UNASSIGNED_DEVICES_LIST_PAGER = 1;
    public static final int DEVICES_LIST_PAGER = 2;

    private int pageFlag;
    private String roomName;
    private String roomUuid;
    private RoomDeviceListAdapter deviceListAdapter;
    private CommonPopupWindow topWindow;  //顶部悬浮窗口
    private CommonPopupWindow bottomWindow;  //底部悬浮窗口

    @Override
    protected RoomDeviceListViewModel getViewModel() {
        BaseViewModelFactroy<BaseBean> myViewModelFactroy = new BaseViewModelFactroy<>(this, this);
        RoomDeviceListViewModel tmp = new ViewModelProvider(this, myViewModelFactroy).get(RoomDeviceListViewModel.class);
        return tmp;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.room_activity_device_list;
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(viewDataBinding.roomToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        setImmersionBar();

        init();
        setLoadSir(viewDataBinding.roomConstraintLayout);
        showLoading();
        viewModel.onLoad();
    }

    private void init() {
        Intent intent = getIntent();
        if (intent != null){
            pageFlag = intent.getIntExtra(PAGER_FLAG, DEVICES_LIST_PAGER);
            roomName = intent.getStringExtra(ROOM_NAME);
            roomUuid = intent.getStringExtra(ROOM_UUID);
        }
        if (roomUuid != null){
            viewModel.setRoomId(roomUuid);
        }
        viewModel.setPagerFlg(pageFlag);
        setTitleText(0);

        if (pageFlag == UNASSIGNED_DEVICES_LIST_PAGER){
            viewDataBinding.roomTopTips.setVisibility(View.VISIBLE);
            deviceListAdapter = new RoomDeviceListAdapter(true);
            deviceListAdapter.setOnItemLongClickListener((adapter, view, position) -> {
                //长按编辑和移动
                showPopupWindow();
                return false;
            });
        }else {
            viewDataBinding.roomTopTips.setVisibility(View.GONE);
            deviceListAdapter = new RoomDeviceListAdapter(roomName);
            deviceListAdapter.setOnItemClickListener((adapter, view, position) -> {
                //点击进入设备设置页面
                RadarBean radarBean = deviceListAdapter.getData().get(position);
                ARouter.getInstance()
                        .build(RouterActivityPath.Dev.PAGE_DEV_HOME)
                        .withSerializable("radarBean", radarBean)
                        .navigation();
            });
            //雷达设置界面，删除雷达，刷新界面
            LiveDatabus.getInstance()
                    .with(Gobal.EVENT_KEY.DEV_COUNT_CHANGE,Integer.class)
                    .observe(this, integer -> onRetryBtnClick());
        }
        viewDataBinding.roomRvDeviceList.setLayoutManager(new GridLayoutManager(this,2));
        viewDataBinding.roomRvDeviceList.setAdapter(deviceListAdapter);

//        List<RadarBean> radarBeans = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            radarBeans.add(new RadarBean("123", "a123456", 0, "test"));
//        }
//        deviceListAdapter.setList(radarBeans);
    }

    private void setImmersionBar() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true)
                .autoDarkModeEnable(true).init();
    }

    private void setTitleText(int deviceCount){
        if (pageFlag == UNASSIGNED_DEVICES_LIST_PAGER){
            if (deviceCount > 0){
                String str = getString(R.string.room_unassigned_devices_title2) + " (" + deviceCount + ")";
                viewDataBinding.roomTitle.setText(str);
                String tips = viewDataBinding.roomTopTips.getText().toString();
                viewDataBinding.roomTopTips.setText(String.format(tips, deviceCount));
            }else {
                viewDataBinding.roomTitle.setText(R.string.room_unassigned_devices_title2);
            }
        }else {
            viewDataBinding.roomTitle.setText(R.string.room_device_list);
        }
    }

    //显示悬浮窗口
    private void showPopupWindow(){
        deviceListAdapter.setShowCheckBox(true);
        // 顶部悬浮窗
        topWindow = new CommonPopupWindow<CommonLayoutTopDialogBinding>(this, R.layout.common_layout_top_dialog) {

            public void setSelectedCount(int count){
                binding.selected.setText(String.format(getString(R.string.dev_selected), String.valueOf(count)));
            }

            @Override
            protected void initEvent(CommonLayoutTopDialogBinding binding) {
                deviceListAdapter.setOnSelect(count -> {
                    setSelectedCount(count);
                });
                setSelectedCount(0);
                binding.selectAll.setOnClickListener(v -> {
                    binding.selectAll.setText(deviceListAdapter.isSelectAll() ? R.string.dev_select_all : R.string.dev_unselect_all);
                    deviceListAdapter.setSelectAll(!deviceListAdapter.isSelectAll());
                    setSelectedCount(deviceListAdapter.isSelectAll() ? deviceListAdapter.getItemCount() : 0);
                });
                binding.cancel.setOnClickListener(v -> {
                    closePopupWindow();
                    deviceListAdapter.setShowCheckBox(false);
                });
            }
        };
        topWindow.showAtLocation(viewDataBinding.getRoot(), Gravity.TOP);

        //底部悬浮窗
        bottomWindow = new CommonPopupWindow<CommonLayoutBottomDialogBinding>(this, R.layout.common_layout_bottom_dialog) {

            @Override
            protected void initEvent(CommonLayoutBottomDialogBinding binding) {
                //移动
                binding.moving.setOnClickListener(v -> {
                    Map<Integer, RadarBean> checkedItems = deviceListAdapter.getCheckedItems();
                    if (null != checkedItems && checkedItems.size() > 0){
//                        Intent intent = new Intent(this, DevBindRoomActivity.class);
//                        startActivityForResult(intent, DevBindRoomActivity.BING_REQUEST_CODE);
                        if (!checkRadarType(checkedItems)){
                            showMoveTips();
                            return;
                        }
                        ARouter.getInstance()
                                .build(RouterActivityPath.Dev.PAGE_DEV_BIND_ROOM)
                                .navigation(RoomDeviceListActivity.this, BING_REQUEST_CODE);
                    }else {
                        ToastUtils.showShort(R.string.dev_move_tips);
                    }
                });
                //删除
                binding.delete.setOnClickListener(v -> {
                    List<String> radarUuid = new ArrayList<>();
                    Map<Integer, RadarBean> checkedItems = deviceListAdapter.getCheckedItems();
                    if(null == checkedItems || checkedItems.size() == 0){
                        ToastUtils.showShort(R.string.dev_del_tips);
                        return;
                    }else{
                        Iterator<Integer> it = checkedItems.keySet().iterator();
                        while(it.hasNext()){
                            Integer key = it.next();
                            radarUuid.add(checkedItems.get(key).getRadarUuid());
                        }
                    }
                    MoveBindRoomBean bean = new MoveBindRoomBean(radarUuid, "");
                    viewModel.deleteRadars(RoomDeviceListActivity.this, bean, new IOperationResult() {
                        @Override
                        public void onSuccess() {
                            closePopupWindow();
                            deviceListAdapter.getCheckedItems().clear();
                            LiveDatabus.getInstance().with(Gobal.EVENT_KEY.REFESH_ROOM, Integer.class).postValue(1);
                            onRetryBtnClick();
                        }

                        @Override
                        public void onFail() {
                            closePopupWindow();
                        }
                    });
                });
            }
        };
        bottomWindow.showAtLocation(viewDataBinding.getRoot(), Gravity.BOTTOM);
    }

    private void closePopupWindow(){
        if (topWindow == null || bottomWindow == null) return;
        topWindow.dismiss();
        bottomWindow.dismiss();
        topWindow = null;
        bottomWindow = null;
    }

    //显示移动设备提示
    private void showMoveTips(){
        CustomTipsDialog tipsDialog = new CustomTipsDialog(this, getString(R.string.common_move_tips));
        tipsDialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                tipsDialog.dismiss();
            }

            @Override
            public void onNegtiveClick() {
                tipsDialog.dismiss();
            }
        });
        tipsDialog.show();
    }

    /**
     * 检查移动的雷达，如果雷达个数大于3，返回false
     * 每个房间assure和wavve雷达都不能超过一台，否则返回false
     * @param map
     * @return
     */
    private boolean checkRadarType(Map<Integer, RadarBean> map){
        if (map.size() > 2) return false;

        int assureCount = 0;
        int wavveCount = 0;
        for (RadarBean r : map.values()){
            if (r.getType() == RadarType.ASSURE){
                assureCount++;
            }else {
                wavveCount++;
            }
            if (assureCount > 1 || wavveCount > 1){
                return false;
            }
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(BING_REQUEST_CODE == requestCode && null != data){
            BindRoomBean bindRoomBean = (BindRoomBean) data.getSerializableExtra("ROOM");
            if(null == bindRoomBean){
                return;
            }

            List<RadarBean> radarBeans = new ArrayList<>();
            Map<Integer, RadarBean> checkedItems = deviceListAdapter.getCheckedItems();
            if(null == checkedItems || checkedItems.size() == 0){
                ToastUtils.showShort(R.string.dev_move_tips);
                return;
            }else{
                Iterator<Integer> it = checkedItems.keySet().iterator();
                while(it.hasNext()){
                    Integer key = it.next();
                    radarBeans.add(checkedItems.get(key));
                }
            }

            MoveBindRoomBean bean = new MoveBindRoomBean(bindRoomBean.getRoomUuid(), radarBeans);
            viewModel.devsBindRoom(this, bean, new IOperationResult() {
                @Override
                public void onSuccess() {
                    closePopupWindow();

                    deviceListAdapter.getCheckedItems().clear();
//                    deviceListAdapter.deleteItem();
                    LiveDatabus.getInstance().with(Gobal.EVENT_KEY.REFESH_ROOM, Integer.class).postValue(1);
                    onRetryBtnClick();
                }

                @Override
                public void onFail() {
                    closePopupWindow();
                }
            });
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
            finish();
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void loadDataSuccess(BaseBean baseBean) {
        if (baseBean instanceof RoomUnassignedBean){
            RoomUnassignedBean bean = (RoomUnassignedBean) baseBean;
            if (bean != null && bean.roomRadarInfo != null && bean.roomRadarInfo.size() > 0){
                deviceListAdapter.setList(bean.roomRadarInfo);
                viewDataBinding.roomTopTips
                        .setText(String.format(getString(R.string.room_unassigned_devices_list_tips),
                                String.valueOf(bean.roomRadarInfo.size())));
                showContent();
            }else {
                showEmpty();
            }
        }else if (baseBean instanceof GetRadarList){
            GetRadarList getRadarList = (GetRadarList) baseBean;
            if (getRadarList != null && getRadarList.getRadarInfo().size() > 0){
                deviceListAdapter.setList(getRadarList.getRadarInfo());
                showContent();
            }else {
                showEmpty();
            }
        }
    }

    @Override
    public void loadDataFail(String decs) {
        ToastUtils.showShort(decs);
        showFailure(decs);
    }
}
